<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar title="搜索结果" left-arrow @click-left="$router.go(-1)" fixed />
    </div>

    <!-- 搜索结果 -->
    <div>
      <van-list
       v-model="loading"
       :finished="finished"
       finished-text="没有更多了"
       @load="onLoad"
       :immediate-check="false"
       >
        <ArticleItem
        v-for="item in articleList"
        :key="item.art_id"
        :artItem="item"
        :isShow="false"
        @click.native="itemClickFn(item.art_id)"
        ></ArticleItem>
      </van-list>
    </div>
  </div>
</template>

<script>
import { searchResultAPI } from '@/api/index.js'
import ArticleItem from '@/components//ArticleItem.vue'

export default {
  name: 'SearchResult',
  data () {
    return {
      page: 1, // 页码
      articleList: [], // 文章列表
      loading: false, // 加载状态
      finished: false // 是否全部加载完
    }
  },
  async created () {
    const { data: res } = await searchResultAPI({
      page: this.page,
      q: this.$route.params.kw
    })
    this.articleList = res.data.results
  },
  methods: {
    // 加载事件
    async onLoad () {
      if (this.articleList.length === 0) return
      this.page++
      const { data: res } = await searchResultAPI({
        page: this.page,
        q: this.$route.params.kw
      })

      if (res.data.results.length === 0) {
        // 没有更多东西
        this.finished = true
        return
      }
      this.articleList = [...this.articleList, ...res.data.results]
      this.loading = false
    },
    // 文章点击跳转详情事件
    itemClickFn (id) {
      this.$router.push({
        path: `/detail?art_id=${id}`
      })
    }
  },
  components: {
    ArticleItem
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
